<template>
  <div v-loading="infoLoading">

    <el-dialog
      :title="fileDialogTitle"
      :visible.sync="fileDialogVisible"
      width="98%"
      top="20px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-form ref="filePostForm" :model="filePostForm" class="form-container" label-width="200px">
        <el-form-item v-if="!readOnly" label="文件" prop="file">
          <el-upload
            class="upload-demo"
            :action="this.$http.defaults.baseURL+'api/gen/file/upload/'"
            :on-success="handleUploadSucc"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-error="uploadError"
            :multiple="false"
            :file-list="fileList"
            :headers="myHeaders"
            :limit="1"
            :on-exceed="handleExceed"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="说明" prop="address">
          <el-input v-model="filePostForm.remark" type="textarea" style="width:800px" rows="10" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="submitFileForm">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      :title="dialogtitle"
      :visible.sync="dialogVisible"
      width="98%"
      top="20px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-alert
        v-if="postForm.shzt===3"
        title="审核未通过"
        type="error"
        :description="'原因：'+hist.auditResult?hist.auditResult:'读取中...'"
        show-icon
      />
      <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container" label-width="200px">
        <el-form-item label="移送案件名称" prop="ysajmc">
          <el-input v-if="!readOnly" v-model="postForm.ysajmc" style="width:600px" />
          <span v-else>{{ postForm.ysajmc }}</span>
        </el-form-item>
        <el-form-item label="移送起诉时间" prop="ysqssj">
          <el-date-picker v-if="!readOnly" v-model="postForm.ysqssj" style="width:200px" value-format="yyyy-MM-dd" />
          <span v-else>{{ postForm.ysqssj }}</span>
        </el-form-item>
        <el-form-item label="移送嫌疑人" prop="xyr">
          <el-select v-if="!readOnly" v-model="xyrlist" multiple placeholder="请选择" style="width:800px;">
            <el-option
              v-for="item in xyrAll"
              :key="item.id"
              :label="item.xm+'(身份证号：'+item.sfzh+(item.disabled?' 已移送':'')+')'"
              :disabled="item.disabled"
              :value="item.id"
            />
          </el-select>
          <span v-else>
            <div v-for="(item,index) in postForm.xyrgkqkList" :key="index">
              {{ item.xm }}(身份证号：{{ item.sfzh }})
            </div>
          </span>
        </el-form-item>
        <el-form-item label="移送罪名" prop="yszm">
          <el-input v-if="!readOnly" v-model="postForm.yszm" type="textarea" style="width:800px" />
          <span v-else>{{ postForm.yszm }}</span>
        </el-form-item>
        <el-form-item label="移送意见" prop="ysyj">
          <el-input v-if="!readOnly" v-model="postForm.ysyj" type="textarea" style="width:800px" />
          <span v-else>{{ postForm.ysyj }}</span>
        </el-form-item>
        <div>
          <upload-files v-if="!infoLoading" :id="postForm.id" :cfajbh="cfajbh" :read-only="readOnly" table="bus_ysscqs" :timestamp="subtimestamp" @updateFj="updateFj" />
        </div>
        <el-form-item style="margin:10px 0">
          <el-button v-if="!readOnly" type="warning" :loading="loading" @click="submitForm(0)">办理中</el-button>
          <el-button v-if="!readOnly" type="success" :loading="loading" @click="submitForm(1)">已完成</el-button>
        </el-form-item>
      </el-form>
      <el-form v-if="auditFlag" ref="auditForm" :model="auditForm" class="form-container" label-width="200px">
        <el-form-item label="是否通过" prop="auditState">
          <el-radio-group v-model="auditForm.auditState">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="0">未通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="auditFlag&&!auditForm.auditState" label="未通过原因" prop="auditResult">
          <el-input v-model="auditForm.auditResult" style="width:810px" />
        </el-form-item>
        <el-form-item style="margin:10px 0">
          <el-button type="success" :loading="loading" @click="submitAudit">审核</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <div v-if="showDuban">
      <supervise v-if="showSupervise()" business-table="bus_ysscqs" :cfajbh="cfajbh" :timestamp="timestamp" />
    </div>
    <h2>详细信息</h2>
    <el-button v-if="unitName==='公安'&&roleName==='录入'" class="filter-item" type="success" icon="el-icon-edit" style="margin:0 0 10px" @click="addnew">
      新增移送审查起诉
    </el-button>
    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <!-- <el-table-column v-if="roleEdit" type="selection" width="50" align="center" /> -->

      <el-table-column
        align="center"
        type="index"
        label="序号"
        width="50px"
        :index="indexMethod"
      />
      <!-- <el-table-column align="center" prop="ajh" label="案件号" width="210px" sortable="custom" />
      <el-table-column align="center" prop="cfajbh" label="处非案件编号" width="130px" sortable="custom" /> -->

      <el-table-column min-width="80px" prop="ysajmc" label="移送案件名称" sortable="custom" />
      <el-table-column width="130px" prop="ysqssj" align="center" label="移送起诉时间" sortable="custom" />
      <el-table-column width="110px" prop="shzt" align="center" label="审核状态" sortable="custom">
        <template slot-scope="scope">
          <span v-if="scope.row.shzt===0" style="color:#000">未提交</span>
          <span v-if="scope.row.shzt===1" style="color:#1890FF">已提交</span>
          <span v-if="scope.row.shzt===2" style="color:#11b95c">审核通过</span>
          <span v-if="scope.row.shzt===3" style="color:#FF4949">审核未通过</span>
        </template>
      </el-table-column>
      <!-- <el-table-column width="105px" prop="lrryxm" align="center" label="录入人员" sortable="custom" />
      <el-table-column width="105px" prop="shryxm" align="center" label="审核人员" sortable="custom" /> -->
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button size="small" icon="el-icon-search" @click="detail(scope.row.id)">详情</el-button>
          <el-button v-if="canEdit(scope.row.gazt)" size="small" type="primary" icon="el-icon-edit" @click="edit(scope.row.id)">修改</el-button>
          <el-popconfirm v-if="canEdit(scope.row.gazt)" title="确定删除该信息吗？" style="margin-left:10px;" @onConfirm="deleteData(scope.row.id)">
            <el-button slot="reference" type="danger" size="small" icon="el-icon-delete">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getData" />

  </div>
</template>

<script>

import uploadFiles from './uploadfilesId.vue'
import supervise from './supervise.vue'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
const defaultForm = {
  ysqssj: '',
  ysajmc: '',
  yszm: '',
  ysyj: '',
  id: null
}
const defaultFileForm = {
  fileid: 0,
  remark: ''
}
const defaultAuditForm = {
  auditResult: '',
  auditState: 1
}
export default {
  name: 'ArticleDetail',
  components: { Pagination, uploadFiles, supervise },
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    showDuban: {
      type: Boolean,
      default: false
    },
    cfajbh: {
      type: String,
      default: ''
    },
    infoid: {
      type: Number,
      default: 0
    },
    ysscqsId: {
      type: Number,
      default: 0
    },
    timestamp: {
      type: Number,
      default: 0
    },
    step: {
      type: String,
      default: ''
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (!value || value === '') {
        // this.$message({
        //   message: '请将表单填写完整',
        //   type: 'error'
        // })
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      xyrlist: [],
      xyrAll: [],
      subtimestamp: 0,
      dialogVisible: false,
      dialogtitle: '',
      list: [],
      total: 0,
      Sortkey: '',
      Isace: '',
      listQuery: {
        page: 1,
        limit: 10
      },
      hist: {},
      auditFlag: false,
      auditForm: Object.assign({}, defaultAuditForm),
      ajh: '',
      ajmc: '',
      fjloading: false,
      fjindex: -1,
      fileList: [],
      fjlList: [],
      fjList: [],
      fileDialogVisible: false,
      fileDialogTitle: '新增',
      myid: 0,
      unitName: '',
      roleName: '',
      deptName: '',
      realName: '',
      myHeaders: {},
      imageUrl: '',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      filePostForm: Object.assign({}, defaultFileForm),
      loading: false,
      deptOption: [],
      userOption: [],
      processUserOption: [],
      priorityOption: [],
      classCodeOption: [],
      flowTypeOption: [],
      rules: {
        ysqssj: [{ validator: validateRequire }],
        ysajmc: [{ validator: validateRequire }]
      },
      processListLoading: false,
      processList: [{ time: '第一次', unit1: '处非办', unit2: '公安局', date: '2021-05-10', limit: '10天', item: '尽快办理', result: '已办结' }, { time: '第二次', unit1: '处非办', unit2: '公安局', date: '2021-05-20', limit: '10天', item: '尽快办理', result: '已办结' }],
      processNow: {},
      mystep: ''
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        if (this.$refs['postForm']) {
          this.$refs['postForm'].resetFields()
        }
        this.mystep = this.step
        this.getXyrAll()
        this.getData()
      },
      immediate: true
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    const day = new Date()
    day.setTime(day.getTime())
    const userinfo = JSON.parse(localStorage.getItem('user'))
    this.unitName = userinfo.unitName
    this.roleName = userinfo.roleName
    // this.postForm.publishTime = day.getFullYear() + '-' + this.add0(day.getMonth() + 1) + '-' + this.add0(day.getDate())
  },
  created() {
  },
  methods: {
    deleteData(id) {
      this.$http
        .get('/api/busYsscqs/removeYsscqsById?id=' + id)
        .then(response => {
          if (response.data.success === true) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getXyrAll()
            this.getData()
          } else {
            console.log('删除失败:' + response.data.message)
            this.$message({
              message: '删除失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getXyrAll() {
      this.infoLoading = true
      if (this.infoid) {
        this.$http
          .get('/api/ga/getGaById?&id=' + this.infoid)
          .then(response => {
            this.infoLoading = false
            if (response.data.success === true) {
              this.xyrAll = []
              this.xyrlist = []
              const gkqkList = response.data.result.gkqkList
              const sfzhs = Array.from(new Set(response.data.result.gkqkList.map(item => item.sfzh))) // 身份证号去重
              sfzhs.forEach(item => {
                const person = gkqkList.filter(it => it.sfzh === item) // 过滤出这个身份证号的所有人
                if (person.find(it => it.ysscqsId)) {
                  this.xyrAll.push({ id: person[0].id, sfzh: person[0].sfzh, xm: person[0].xm, disabled: true })
                } else {
                  this.xyrAll.push({ id: person[0].id, sfzh: person[0].sfzh, xm: person[0].xm, disabled: false })
                }
              })
              // response.data.result.gkqkList.filter(item => !item.ysscqsId).map(item => { return { id: item.id, sfzh: item.sfzh, xm: item.xm } }).forEach(
              //   item => {
              //     if (!this.xyrAll.find(it => it.sfzh === item.sfzh)) {
              //       this.xyrAll.push(item)
              //     }
              //   }
              // )
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.infoLoading = false
          })
      } else {
        this.$nextTick(() => {
          this.infoLoading = false
          this.xyrAll = []
        })
      }
    },
    detail(id) {
      if (this.$refs['postForm']) {
        this.$refs['postForm'].resetFields()
      }
      this.subtimestamp = new Date().getTime()
      this.postForm.id = id
      this.readOnly = true
      this.dialogtitle = '查看'
      this.dialogVisible = true
      this.getYsscqsById(id)
    },
    edit(id) {
      this.subtimestamp = new Date().getTime()
      this.postForm.id = id
      this.readOnly = false
      this.dialogtitle = '修改'
      this.dialogVisible = true
      this.getYsscqsById(id)
    },
    addnew() {
      this.postForm = Object.assign({}, defaultForm)
      this.xyrlist = []
      this.readOnly = false
      this.dialogtitle = '新增'
      this.dialogVisible = true
    },
    getYsscqsById(id) {
      this.$http
        .get('/api/busYsscqs/getYsscqsById?&id=' + id)
        .then(response => {
          if (response.data.success === true) {
            this.postForm = response.data.result
            if (this.postForm.xyrgkqkList && this.postForm.xyrgkqkList.length > 0) {
              this.postForm.xyrgkqkList.forEach(item => {
                this.xyrAll.splice(this.xyrAll.findIndex(it => it.sfzh === item.sfzh), 1)
                this.xyrAll.push({ id: item.id, sfzh: item.sfzh, xm: item.xm, disabled: false })
              })
              this.xyrlist = this.postForm.xyrgkqkList.map(item => item.id)
            }
            if (this.postForm.shzt === 1 && this.unitName === '公安' && this.roleName === '审核') {
              this.auditFlag = true
            } else {
              this.auditFlag = false
            }
            if (response.data.result.shzt === 3) {
              this.getHist()
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.infoLoading = false
        })
    },
    canEdit(zt) {
      if (this.unitName === '公安' && this.roleName === '录入') {
        if (zt === 1 || zt === 2) {
          return false
        } else {
          return true
        }
      } else {
        return false
      }
    },
    indexMethod(index) {
      index = (index + 1) + (this.listQuery.page - 1) * this.listQuery.limit
      return index
    },
    showSupervise() {
      return true
      // return JSON.parse(localStorage.getItem('user')).unitName === '处非办' || JSON.parse(localStorage.getItem('user')).unitName === '公安' || JSON.parse(localStorage.getItem('user')).unitName === '督查室' || JSON.parse(localStorage.getItem('user')).unitName === '政法委'
    },
    // 提交审核
    submitAudit() {
      // if (this.auditForm.auditState === 0 && this.auditForm.auditResult === '') {
      //   this.$message({
      //     message: '审核不通过请说明原因',
      //     type: 'error'
      //   })
      // } else {
      const para = {
        id: this.postForm.id,
        auditResult: this.auditForm.auditResult,
        auditState: this.auditForm.auditState
      }
      this.loading = true
      this.$http
        .post('/api/busYsscqs/audit', para)
        .then(response => {
          this.loading = false
          if (response.data.success === true) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.dialogVisible = false
            this.auditForm = Object.assign({}, defaultAuditForm)
            this.postForm = Object.assign({}, defaultForm)
            this.xyrlist = []
            this.xyrAll = []
            this.loading = false
            this.getXyrAll()
            this.getData(this.cfajbh)
          } else {
            console.log('操作失败:' + response.data.message)
            this.$message({
              message: '操作失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.loading = false
        })
      // }
    },
    updateFj(list) {
      this.fjList = list
    },
    download(item) {
      window.open(this.$http.defaults.baseURL + 'api/gen/file/download?id=' + item.id)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`一次最多只能上传一个文件`)
    },
    uploadError(err) {
      console.log(err)
      this.$message({
        message: '上传失败:' + err,
        type: 'error',
        duration: 10000
      })
    },
    handleUploadSucc(response, file, fileList) {
      if (response.success) {
        this.$message({
          type: 'success',
          message: '上传成功!'
        })
        this.fileList.push({ id: response.result[0].id, name: response.result[0].fileName + '.' + response.result[0].fileType, url: this.$http.defaults.baseURL + 'api/gen/file/download?id=' + response.result[0].id, dataCreateDatetime: response.result[0].dataCreateDatetime })
      } else {
        this.$message({
          message: '上传失败:' + response.message,
          type: 'error',
          duration: 10000
        })
      }
    },
    dateFormat(date) {
      console.log('日期转换')
      console.log(date)
      return date.getFullYear().toString() + '-' + (date.getMonth() + 1).toString() + '-' + date.getDate().toString()
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      const fid = file.id
      this.$http.get('api/gen/file/remove?id=' + fid).then(res => {
        if (res.data.success === true) {
          this.fileList = this.fileList.filter(item => item.id !== fid)
          this.$message({
            message: '删除成功！',
            type: 'success'
          })
        }
      })
    },
    handleDeleteFile(index) {
      this.fjList.splice(index, 1)
    },
    submitFileForm() {
      if (this.fileList && this.fileList.length > 0) {
        console.log(this.fileList)
        this.fileList[0].remark = this.filePostForm.remark
        this.filePostForm = Object.assign({}, defaultFileForm)
        if (this.fjindex === -1) {
          this.fjList.push(this.fileList[0])
        } else {
          this.fjList[this.fjindex] = this.fileList[0]
          this.fjindex = -1
        }
        this.fileList = []
        this.fileDialogVisible = false
      } else {
        this.$message({
          message: '请上传文件',
          type: 'error'
        })
      }
    },
    editFile(index, item) {
      this.fileList = []
      this.fileList.push(item)
      this.filePostForm.remark = item.remark
      this.filePostForm.dataCreateDatetime = item.dataCreateDatetime
      this.fjindex = index
      this.fileDialogVisible = true
      this.fileDialogTitle = '修改'
    },
    addFile() {
      this.filePostFormForm = Object.assign({}, defaultFileForm)
      this.fileDialogVisible = true
      this.fileDialogTitle = '新增'
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log('test')
      if (res.success) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
        this.imageUrl = res.result[0].id
        // this.fileList = []
        // this.files = []
      } else {
        this.$message({
          message: '上传失败:' + res.message,
          type: 'error'
        })
      }
    },
    getFj(id) {
      const para = {
        pageNum: 1,
        pageSize: 1000,
        cfajbh: id,
        businessTable: 'bus_ysscqs'
      }
      this.fjloading = true
      this.$http
        .post('/api/gen/file/search', para)
        .then(response => {
          this.loading = false
          if (response.data.success === true) {
            this.fjList = response.data.result.records.map(item => { return { name: item.fileName + '.' + item.fileType, remark: item.remark, id: item.id, dataCreateDatetime: item.dataCreateDatetime } })
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(function(error) {
          console.log(error)
          this.fjloading = false
        })
    },
    getHist() {
      const para = {
        actName: '移送审查起诉',
        actState: 1,
        cfajbh: this.postForm.id,
        pageNum: 1,
        pageSize: 1
        // publishTime: this.listQuery.publishTime,
        // title: this.listQuery.title
      }
      this.$http
        .post('/api/busHist/queryByPage', para)
        .then(response => {
          if (response.data.success === true) {
            this.hist = response.data.result.records[0]
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getData() {
      if (this.cfajbh) {
        const para = {
          id: this.postForm.id,
          cfajbh: this.cfajbh,
          orderField: this.Sortkey,
          orderType: this.Isace,
          pageNum: this.listQuery.page,
          pageSize: this.listQuery.limit
        }
        this.listLoading = true
        this.$http
          .post('/api/busYsscqs/queryPage', para)
          .then(response => {
            this.listLoading = false
            if (response.data.success === true) {
              this.list = response.data.result.records
              this.total = response.data.result.total
              console.log('this.ysscqsId')
              console.log(this.ysscqsId)
              if (this.ysscqsId) {
                this.list = this.list.filter(item => item.id === this.ysscqsId)
                this.total = 1
              }
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.listLoading = false
          })
      }
    },
    sortChange(column, prop, order) {
      this.Sortkey = column.prop
      if (column.order === 'ascending') {
        this.Isace = 'asc'
      } else {
        this.Isace = 'desc'
      }
      this.getData()
    },
    submitForm(flag) {
      if (this.postForm.ysqssj) {
        this.$refs.postForm.validate(valid => {
          if (valid) {
            const para = {
              id: this.postForm.id ? this.postForm.id : null,
              cfajbh: this.cfajbh,
              ysqssj: this.postForm.ysqssj,
              ysajmc: this.postForm.ysajmc,
              yszm: this.postForm.yszm,
              ysyj: this.postForm.ysyj,
              xyrIds: this.xyrlist,
              files: this.fjList.map(item => { return { fileId: item.id, remark: item.remark, classCode: item.classCode } }),
              shzt: flag
            }
            this.loading = true
            this.$http
              .post('/api/busYsscqs/saveYsscqs', para)
              .then(response => {
                this.loading = false
                if (response.data.success === true) {
                  this.$message({
                    message: '保存成功',
                    type: 'success'
                  })
                  this.dialogVisible = false
                  this.postForm = Object.assign({}, defaultForm)
                  this.xyrlist = []
                  this.xyrAll = []
                  this.loading = false
                  this.getXyrAll()
                  this.getData(this.cfajbh)
                } else {
                  console.log('保存失败:' + response.data.message)
                  this.$message({
                    message: '保存失败:' + response.data.message,
                    type: 'error'
                  })
                }
              })
              .catch(function(error) {
                console.log(error)
                this.loading = false
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$message({
          message: '请填写移送起诉时间',
          type: 'error'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
